//
//  LTNetworkTools.swift
//  微博08
//
//  Created by 123 on 16/3/2.
//  Copyright © 2016年 Tsr. All rights reserved.
//

import UIKit
import AFNetworking

// 枚举是值类型
// 类是:指针,引用
enum LTNetworkToolsError: Int {
    // 方式2
    case AccessTokenEmpty = -1
    case UidEmpty = -2
    
    // 方式2
    // 枚举可以有属性
    var errorMessage: String {
        get {
            switch self {
            case AccessTokenEmpty: return "AccessToken 没有值"
            case UidEmpty: return "Uid 没有值"
            }
        }
    }
    
    // 方式3: 将NSError的创建也封装到枚举里面
    // 枚举可以有方法
    func error() -> NSError {
        return NSError(domain: "cn.itcast.net", code: self.rawValue, userInfo: ["errorMessage" : self.errorMessage])
    }
}

class LTNetworkTools: NSObject {
    
    let afnManager: AFHTTPSessionManager
    
    // 单例
    static let sharedInstance: LTNetworkTools = LTNetworkTools()
    
    // private表示私有方法,除这个文件外的其它类是不知道这个方法的
    private override init() {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        afnManager = AFHTTPSessionManager(baseURL: baseURL)
        
        afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        super.init()
    }
    
    // MARK: Oauth授权相关
    let client_id = "1144660943"
    let client_secret = "0839a076ff4a8ba51fd934f8af5ab801"
    let redirect_uri = "http://www.baidu.com/"
    let oauthUrl = "https://api.weibo.com/oauth2/authorize"
    
    // 获得oauth授权的登录界面
    func oauthLoginUrl() -> NSURL {
        let urlString = oauthUrl + "?" + "client_id=" + client_id + "&" + "redirect_uri=" + redirect_uri
        
        return NSURL(string: urlString)!
    }
    
    // 获取access_token
    func loadAccessToken(code: String, accessTokenFinished: finishedCallBack) {
        // 3.3请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 3.4请求参数
        let parameter = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        // 3.5发送POST请求
        afnManager.POST(urlString, parameters: parameter, progress: nil, success: { (_, response) -> Void in
            
            let dict = response as? [String: AnyObject]
            // 获得数据,调用闭包
            accessTokenFinished(result: dict, error: nil)
            }) { (_, error) -> Void in
                accessTokenFinished(result: nil, error: error)
        }
        
    }
    
    // 发送GET请求
    func loadUserInfo(finished: finishedCallBack) {
        
        // 3.判断access_token
//        guard let access_token = LTUserAccountViewModel.sharedInstance.userAccount?.access_token else {
//            let error = LTNetworkToolsError.AccessTokenEmpty.error()
//            finished(result: nil, error: error)
//            return
//        }
        
        // 4.判断uid
        guard let uid = LTUserAccountViewModel.sharedInstance.userAccount?.uid else {
            let error = NSError(domain: "cn.itcast.net", code: -2, userInfo: ["errorMessage" : "Uid 没有值"])
            finished(result: nil, error: error)
            return
        }
        
        // 5.url
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 6.准备参数
        let paramaters = ["uid": uid]
        
        // 7.发送请求
//        afnManager.GET(urlString, parameters: paramaters, progress: nil, success: { (_, result) -> Void in
//            // 8.调用闭包
//            finished(result: result as? [String: AnyObject], error: nil)
//            }) { (_, error) -> Void in
//                finished(result: nil, error: error)
//        }
        requestGET(urlString, parameters: paramaters, finished: finished)
    }
    
    // 加载微博数据
    func loadStatus(finished: finishedCallBack) {
        
//        guard let access_token = LTUserAccountViewModel.sharedInstance.userAccount?.access_token else {
//            
//            // 方式3 将NSError的创建也封装到枚举里面
//            let error = LTNetworkToolsError.AccessTokenEmpty.error()
//            finished(result: nil, error: error)
//            return
//        }
        
        // url
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 参数
//        let parameters = ["access_token":access_token]
        
//        afnManager.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
//            finished(result: result as? [String: AnyObject], error: nil)
//            }) { (_, error) -> Void in
//                finished(result: nil, error: error)
//        }
        requestGET(urlString, parameters: nil, finished: finished)
    }
    
    // 定义闭包
    typealias finishedCallBack = (result: [String: AnyObject]?, error: NSError?) -> ()
    
    // 封装AFN的GET请求
    private func requestGET(urlString: String, var parameters: [String: AnyObject]?,finished: finishedCallBack) {
        
        guard let access_token = LTUserAccountViewModel.sharedInstance.userAccount?.access_token else {
            let error = LTNetworkToolsError.AccessTokenEmpty.error()
            finished(result: nil, error: error)
            return
        }
        
        // 当别人没有传入请求参数,创建请求参数
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        
        // 给参数拼接access_token,添加 ["access_token": access_token]
        parameters!["access_token"] = access_token
        
        // GET网络请求
        afnManager.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            finished(result: result as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
        
    }
    
}
